import logging
from logging.handlers import TimedRotatingFileHandler
from pathlib import Path

LOG_DIR = Path("logs")
LOG_DIR.mkdir(exist_ok=True)

DEF_FMT = "[%(asctime)s] [%(levelname)s] [%(name)s:%(lineno)d] %(message)s"
DEF_DATE_FMT = "%Y-%m-%d %H:%M:%S"


def get_logger(
        name: str = None,
        *,
        level: str = "INFO",
        log_dir: Path = LOG_DIR,
        file_prefix: str = "app",
        fmt: str = DEF_FMT,
        date_fmt: str = DEF_DATE_FMT,
        console: bool = True,
        backup_days: int = 7,
) -> logging.Logger:
    """
    获取已配置好的 logger
    :param name:          模块名，None 时返回 root
    :param level:         日志级别字符串  DEBUG/INFO/WARNING/ERROR/CRITICAL
    :param log_dir:       日志文件夹
    :param file_prefix:   日志文件名前缀
    :param fmt:           格式模板
    :param date_fmt:      时间格式
    :param console:       是否输出到控制台
    :param backup_days:   保留天数（按天滚动）
    :return:              配置好的 logger
    """
    logger = logging.getLogger(name)
    if logger.hasHandlers():  # 避免重复 addHandler
        return logger

    logger.setLevel(getattr(logging, level.upper(), logging.INFO))

    formatter = logging.Formatter(fmt, date_fmt)

    # 1. 文件处理器（按天分割，backup_days 份）
    file_path = log_dir / f"{file_prefix}.log"
    file_handler = TimedRotatingFileHandler(
        file_path, when="midnight", interval=1, backupCount=backup_days, encoding="utf-8"
    )
    file_handler.setFormatter(formatter)
    logger.addHandler(file_handler)

    # 2. 控制台处理器
    if console:
        console_handler = logging.StreamHandler()
        console_handler.setFormatter(formatter)
        logger.addHandler(console_handler)

    return logger
